package com.heima.user.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @作者 itcast
 * @创建日期 2021/4/20 11:34
 **/
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 1. 参数校验   authorId     operation 必须是 0 或 1
        if(dto.getAuthorId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"作者ID不存在");
        }
        if(dto.getOperation().intValue()!=0 && dto.getOperation().intValue()!=1 ){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"关注类型错误");
        }
        // 2. 获取当前登录人信息
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if(loginUser == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"请先登录后在关注作者");
        }
        // 3. 查询作者信息
        ApAuthor author = articleFeign.selectById(dto.getAuthorId());
        if (author == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的作者信息不存在");
        }
        if(loginUser.getId() == author.getUserId()){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"不可以自己关注自己");
        }
        // 4. 查询作者对应user信息
        // 5. 根据operation状态值 判断 是 取关 还是 关注
        if(dto.getOperation().intValue() == 0){
            followByUserId(loginUser.getId(),author,dto.getArticleId());
        }else {
            followCancelByUserId(loginUser.getId(),author.getUserId());
        }
        return ResponseResult.okResult();
    }

    /**
     * 取消关注
     * @param loginUserId
     * @param authorUserId
     */
    private void followCancelByUserId(Integer loginUserId, Integer authorUserId) {
        // 删除 关注信息表中相关数据
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId,loginUserId)
                .eq(ApUserFollow::getFollowId,authorUserId));
        // 删除 粉丝信息表中相关数据
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId,authorUserId)
                .eq(ApUserFan::getFansId,loginUserId));
    }

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 关注方法
     * @param loginUserId
     * @param author
     */
    private void followByUserId(Integer loginUserId, ApAuthor author,Long articleId) {
        // 查看是否已经关注过
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, loginUserId)
                .eq(ApUserFollow::getFollowId, author.getUserId())
        );
        if (apUserFollow != null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"你已经关注过该作者");
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(loginUserId);
        apUserFollow.setFollowId(author.getUserId());
        apUserFollow.setFollowName(author.getName());
        apUserFollow.setLevel((short)0);
        apUserFollow.setIsNotice(false);
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow); // 插入关注信息
        FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
        behaviorDto.setArticleId(articleId);
        behaviorDto.setFollowId(author.getUserId());
        behaviorDto.setUserId(loginUserId);
        // 发送关注消息 到行为微服务
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(behaviorDto));
        // 查看是否已经成为粉丝
        ApUserFan apUserFan = apUserFanMapper.selectOne(
                Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getUserId, author.getUserId())
                        .eq(ApUserFan::getFansId, loginUserId)
        );
        if(apUserFan!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"你已经成为该作者的粉丝");
        }
        ApUser apUser = apUserMapper.selectById(loginUserId);

        apUserFan = new ApUserFan();
        apUserFan.setUserId(author.getUserId());
        apUserFan.setFansId(Long.valueOf(loginUserId));
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel((short)0);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setIsDisplay(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsShieldComment(false);
        apUserFanMapper.insert(apUserFan); // 插入粉丝信息
    }
}
